﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Huluwa;
public class DanmakuManager : MonoBehaviour
{

    public GameObject danmakuPrefab;
    public Vector2 spawnOffset;
    public float spawnSpeed;
    public Vector2 spawnDirection;
    public int minDanmakuCount = 10;
    public GAME_MODE mode;
    public TextAsset ai_words;
    private string[] ai_strs;
    private static System.Random rd = new System.Random();

    WordAnalyzer wordAnalyzer;
    bool isSingleMode = true;
    // Start is called before the first frame update
    void Start()
    {
        GlobalConfig.Instance.mode = mode;
        GlobalConfig.Instance.danmakuCount = 0;
        // 如果是单机模式，那么就自动生成弹幕
        if (GlobalConfig.Instance.mode == GAME_MODE.singleMode)
        {
            StopAllCoroutines();
            StartCoroutine(AutoGenerateDanmaku());
            isSingleMode = true;
        }
        else
        {
            isSingleMode = false;
            NetworkModule.Instance.Init();
            NetworkModule.Instance.OnRecvMessage = OnRecvMsg;
            if (minDanmakuCount > 0)
            {
                StopAllCoroutines();
                StartCoroutine(AIAutoGenerateDanmaku());
            }
        }

        if (spawnSpeed == 0)
        {
            spawnSpeed = GlobalConfig.Instance.DanmakuMoveSpeed;
        }

        GameManager.Instance.EventOnChapterChange -= OnChapterChange;
        GameManager.Instance.EventOnChapterChange += OnChapterChange;

        GameObject go = GameObject.Find("WordAnalyzer");
        wordAnalyzer = go.GetComponent<WordAnalyzer>();

        ai_strs = ai_words.text.Split('\n');
    }
    public void OnChapterChange(int i)
    {
        NetworkModule.Instance.SendChapterChangeMessage(i);
    }
    IEnumerator AutoGenerateDanmaku()
    {
        while (true)
        {
            yield return new WaitForSeconds(GlobalConfig.Instance.generateDanmakuSpeed);
            //Debug.Log(string.Format("Timer2 is up !!! time=${0}", Time.time));
            if (GlobalConfig.Instance.mode == GAME_MODE.singleMode || (GlobalConfig.Instance.mode == GAME_MODE.networkMode && minDanmakuCount >= GlobalConfig.Instance.danmakuCount))
            {
                Message msg = new Message();
                int idx = (int)(rd.NextDouble() * ai_strs.Length);
                msg.AutoGenerate(ai_strs[idx],isSingleMode);
                SpawnDanmaku(msg);
            }
        }
    }
    IEnumerator AIAutoGenerateDanmaku()
    {
        while (true)
        {
            yield return new WaitForSeconds(GlobalConfig.Instance.AIGenerateDanmakuSpeed);
            Debug.Log(string.Format("Timer2 is up !!! time=${0}", Time.time));
            int currentCount = GlobalConfig.Instance.danmakuCount;
            if (GlobalConfig.Instance.mode == GAME_MODE.networkMode && minDanmakuCount >= currentCount)
            {
                Message msg = new Message();
                int idx = (int)(rd.NextDouble() * ai_strs.Length);
                msg.AutoGenerate(ai_strs[idx],isSingleMode);
                SpawnDanmaku(msg);
            }
        }
    }
    // Update is called once per frame
    void Update()
    {

    }

    void OnRecvMsg(Message data)
    {
        Debug.Log("recv:" + data.content + "<--->" + data.nickname);
        data.t = rd.Next(2);

        SpawnDanmaku(data);
    }

    public void SpawnDanmaku(Message data)
    {
        GlobalConfig.Instance.danmakuCount++;
        Vector3 pos = Vector3.zero;
        pos.y = Camera.main.transform.position.y;
        pos.y += data.GetYOffset();
        pos.y += UnityEngine.Random.Range(-0.01f, 0.01f);

        pos.x += data.GetXOffset();

        if (wordAnalyzer.CheckNegative(data.content))
        {
            data.atti = DanmakuType.harmful;
        }
        if (wordAnalyzer && wordAnalyzer.CheckPositive(data.content))
        {
            if (data.atti == DanmakuType.harmful)
            {
                data.atti = DanmakuType.neutral;
            }
            else
            {
                data.atti = DanmakuType.helpful;
            }
        }
        //random from direction

        // pos.y += Screen.height * data.pos;
        GameObject Prefab = null;

        if (data.atti == DanmakuType.harmful)
        {
            Prefab = (GameObject)Resources.Load(GlobalConfig.Instance.danmaku_N);
        }
        else if (data.atti == DanmakuType.helpful)
        {
            Prefab = (GameObject)Resources.Load(GlobalConfig.Instance.danmaku_P);
        }
        else
        {
            Prefab = (GameObject)Resources.Load(GlobalConfig.Instance.danmaku_0);
        }
        GameObject spawnedObj = null;

        if (Prefab != null)
        {
            spawnedObj = Instantiate(Prefab, pos, Quaternion.identity);
        }
        if (spawnedObj == null)
        {
            spawnedObj = Instantiate(danmakuPrefab, pos, Quaternion.identity);
        }
        Danmaku danmaku = spawnedObj.GetComponent<Danmaku>();
        string text = string.Format("{0}:{1}", data.nickname, data.content);
        danmaku.SetText(text);
        danmaku.SetVelocity(spawnSpeed * spawnDirection * data.dir());
        danmaku.SetData(data);// data.atti;
        danmaku.SetPosition(danmaku.transform.position + Vector3.left * data.dir() * danmaku.GetWidth() / 2f);

    }

}
